package com.example.pt.service;

import com.example.pt.entity.TorrentFileES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TorrentFileESSearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public List<TorrentFileES> searchByKeyword(String info) {
        Query query = buildWeightedQuery(info);
        SearchHits<TorrentFileES> searchHits = elasticsearchTemplate.search(query, TorrentFileES.class);
        return searchHits.stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
    }

    private Query buildWeightedQuery(String info) {
        Criteria mainCriteria = new Criteria("status").is(1);

        if (StringUtils.hasText(info)) {
            // 通过重复添加条件实现权重（title权重2倍于description）
            Criteria titleCriteria = new Criteria("title").matches(info).boost(2.0f);
            Criteria descCriteria = new Criteria("description").matches(info).boost(1.0f);

            // 组合加权条件
            Criteria weightedCriteria = new Criteria().or(titleCriteria)
                    .or(titleCriteria) // 重复添加以增加权重
                    .or(descCriteria);

            mainCriteria = mainCriteria.subCriteria(weightedCriteria);
        }

        return new CriteriaQuery(mainCriteria)
                .addSort(Sort.by(
                        Sort.Order.desc("_score"),  // ES相关度评分排序
                        Sort.Order.desc("uploadTime")
                ));
    }
}